﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace PlusPlusPaint.Tools
{
    abstract class RectangleShapedObjectCreationTool : TwoPointTool
    {
        #region properties
        /// <summary>
        /// True if the tool must be initially applied to an entirely new
        /// layer.  As all toolTypes derived from this concern themselves with
        /// creating an entirely new objects, all must demand new layers.
        /// </summary>
        public override bool DemandsNewLayer
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Returns true if the tool can work on a brand new layer.
        /// </summary>
        // If we demand a new layer, we must be willing to work on it.
        public override bool AcceptsNewLayer
        {
            get
            {
                return true;
            }
        }
        #endregion

        #region abstract methods
        protected abstract void UpdatePreview(Point begin, Point end);
        protected abstract void Complete();
        #endregion

        #region overrides
        public override Layers.ILayer SuggestNewLayer()
        {
            return new Layers.VisualObjectLayer();
        }

        public override bool AcceptableLayer(Layers.ILayer l)
        {
            return l.GetType().IsInstanceOfType(typeof(Layers.VisualObjectLayer));
        }

        public override void HandleMouseDrag(MouseEventArgs mea)
        {
            clearPreview();
            this.UpdatePreview(this.Origin.Value, mea.Location);
        }

        public override void HandleMouseUp(MouseEventArgs mea)
        {
            base.HandleMouseUp(mea);
            clearPreview();
            this.Complete();
            this.Layer.Invalidate();
        }
        #endregion

        #region private methods
        private void clearPreview()
        {
            Graphics.FromImage(Preview).Clear(Color.Transparent);
        }
        #endregion

        #region static methods
        public static Rectangle GetBoundingRectangle(Point p1, Point p2)
        {
            return new Rectangle(
                Math.Min(p1.X, p2.X),
                Math.Min(p1.Y, p2.Y),
                Math.Abs(p1.X - p2.X),
                Math.Abs(p1.Y - p2.Y)
            );
        }
        #endregion
    }
}
